<script setup>
import { inject, ref, watch } from 'vue'
import { showLoadingToast } from 'vant'
import 'vant/es/toast/style'
import { onMounted } from 'vue'
defineOptions({
  name: 'goodList'
})
const props = defineProps(['goods'])
const flush = inject('togHomeData')
const name = ref(0)
onMounted(() => (list.value.length ? '' : flush()))
const tog = (a) => {
  if (name.value === a.name) return
  ;[list.value, name.value] = [[], a.name]
  flush({
    page: 1,
    sales: a.name === 0 ? 1 : 0,
    recommend: a.name === 1 ? 1 : 0,
    new: a.name === 2 ? 1 : 0
  })
}
const list = ref([])
const loading = ref(false)
const finished = ref(false)
let a = false

const onLoad = () => {
  if (!a) return (a = true)
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 500,
    closeOnClick: true
  })
  flush({
    page: props.goods.current_page + 1,
    sales: a.name === 0 ? 1 : 0,
    recommend: a.name === 1 ? 1 : 0,
    new: a.name === 2 ? 1 : 0
  })
}
watch(
  () => props.goods,
  (val) => {
    if (val.data.length) {
      list.value.push(...val.data)
      loading.value = false
    } else finished.value = true
  }
)
</script>

<template>
  <van-tabs
    class="mt-4"
    @click-tab="tog"
    color="red"
    title-inactive-color="gray"
    title-active-color="red"
  >
    <van-tab title="畅销"></van-tab>
    <van-tab title="新书"></van-tab>
    <van-tab title="精选"></van-tab>
  </van-tabs>

  <van-list
    v-model:loading="loading"
    :finished="finished"
    finished-text="没有更多了"
    @load="onLoad"
    class="mb-5"
  >
    <van-row justify="between" class="bg-white" :gutter="[20, 20]">
      <van-col span="12" v-for="item in list" :key="item.id">
        <goodListItem :info="item"></goodListItem>
      </van-col>
    </van-row>
  </van-list>
</template>

<style scoped lang="scss"></style>
